package cn.edu.dlut.port.isp.profile;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.edu.dlut.port.isp.date.USLocalDateFormatter;

@Controller
public class ProfileController {
	private UserProfileSession userProfileSession;

	@Autowired
	public ProfileController(UserProfileSession userProfileSession) {
		this.userProfileSession = userProfileSession;
	}

	@RequestMapping("/register")
	public String register(ProfileForm profileForm) {
		return "profile/register";
	}

	@ModelAttribute("dateFormat")
	public String localeFormat(Locale locale) {
		return USLocalDateFormatter.getPattern(locale);
	}

	@ModelAttribute
	public ProfileForm getProfileForm() {
		return userProfileSession.toForm();
	}

	@RequestMapping(value = "/register", params = { "save" }, method = RequestMethod.POST)
	public String registerUser(@Valid ProfileForm profileForm, BindingResult bindingResult) {
		System.out.println(bindingResult.getErrorCount());
		if (bindingResult.hasErrors()) {
			System.out.println(bindingResult.getObjectName());
			return "profile/register";
		}
		System.out.println("save ok\t" + profileForm.toString());
		userProfileSession.saveForm(profileForm);

		return "redirect:/register";
	}

	@RequestMapping(value = "register", params = { "addInterest" })
	public String addRow(ProfileForm profileForm) {
		profileForm.getInterests().add("java");
		return "profile/register";
	}

	public String removeRow(ProfileForm profileForm, HttpServletRequest req) {
		Integer rowId = Integer.valueOf(req.getParameter("removeInterest"));
		profileForm.getInterests().remove(rowId.intValue());
		return "profile/register";
	}
}